package com.raulraja.util.aop.profile;


import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;

public class MethodProfiler {

	private final static Logger logger = Logger.getLogger(MethodProfiler.class);

	/**
	 * Intercepts methods that declare com.company.project.util.aop.profiler.Profile and prints out the time it takes to complete
	 * @param pjp proceeding join point
	 * @return the intercepted method returned object
	 * @throws Throwable in case something goes wrong in the actual method call
	 */
	public Object profileMethod(ProceedingJoinPoint pjp) throws Throwable {
		try {
			final boolean DEBUG = logger.isDebugEnabled();
			long start = System.currentTimeMillis();
			// Parse out the first arg
			String arg1 = "";
			Object[] pjpArgs = pjp.getArgs();
			if ((pjpArgs != null) && (pjpArgs.length > 0) && (pjpArgs[0] != null)) {
				arg1 = pjpArgs[0].toString();
			}
			String logPrefix = null;
			if (DEBUG) {
				logPrefix = pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() + " " + arg1;
				logger.debug(logPrefix + " START");
			}
			Object retVal = pjp.proceed();
			long end = System.currentTimeMillis();
			long differenceMs = end - start;
			if (DEBUG) {
				logger.debug(logPrefix + " RETURN in " + differenceMs + " ms");
			}
			return retVal;
		}
		catch (Throwable t) {
			logger.error("Interceptor caught error: " + t, t);
			throw t;
		}
	}
}
